<?php

namespace App\Jobs;

use App\Contract\OrderType;
use App\Http\Service\DeviceService;
use App\Model\Agent;
use App\Model\AgentAmountLog;
use App\Model\Bill;
use App\Model\BillPay;
use App\Model\Business;
use App\Model\CashDisabled;
use App\Model\Device;
use App\Model\Message;
use App\Model\UserAmountLog;
use App\Model\UserCashLog;
use App\Service\baofu\Util\Tools;
use App\Service\BaofuPay;
use App\User;
use App\Utils\Result;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;

class CheckOrder implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
    private $order_no;
    private $hand;
    public $tries = 1;
    public $timeout = 10;
    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($order_no, $hand = 1)
    {
        $this->order_no = $order_no;
        $this->hand = $hand;
        //因为要导入大文件 需要很久时间
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        try{
            Redis::setex('CHECK_CACHE_'.$this->order_no,60*60*24*3,1);
            Log::info('queue-check:'.$this->order_no);
            $order = \App\Model\Order::query()->where('order_no',$this->order_no)->first();
            if($order && $order->recharge_status != 3){
                $user = User::query()->where('id',$order->user_id)->first();
                $device = Device::query()->where('id',$order->device_id)->first();
                Log::info($this->order_no.'--before:'.$order->device_du.'after:'.$device->du);
                 if($device->du > ($order->device_du+$order->du*0.2) || $this->hand == 2){
                     $order->recharge_status = 3;
                     $order->save();
                     if($order->type == OrderType::TEMP){
                         $order->status = 5;
                         $order->save();
                         return ;
                     }
                     $service = app()->make(DeviceService::class);
                     $service->addRechargeLog($order->device_id, $order->du, $order->pay_amt,$user,$order->paid_at);
                     $amount = $order->pay_amt - $order->fee;
                     if ($order->device_id) {
                         $deviceModel = Device::query()->where('id', $order->device_id)->first();
                         if ($deviceModel->agent_id) {
                             $agentModel = Agent::query()->where('id', $deviceModel->agent_id)->first();
                             $allRate = number_format($order->pay_amt * (Agent::MAX_RATE / 100), 2,'.', '');
                             try {
                                 if ($agentModel->pid) {
                                     $firstAgent = Agent::query()->where('id', $agentModel->pid)->first();
                                     $agentType = $firstAgent->type;
                                 } else {
                                     $firstAgent = $agentModel;
                                     $agentType = $agentModel->type;
                                 }
                                 if ($agentType == 2) {
                                     $firstFee = $deviceFee = number_format($firstAgent->service * $order->du, 2, '.', '');
                                     if($firstAgent->rate > 0){
                                         $deviceProfit = $amount*($firstAgent->rate/100);
                                     }else{
                                         $deviceProfit = 0;
                                     }
                                     $amount -= $deviceFee;
                                     if ($agentModel->pid && $firstAgent->service > 0) {
                                         $secondFee = number_format(($firstAgent->service * $agentModel->service / 100) * $order->du, 2, '.', '');
                                         if($secondFee+$deviceProfit > $deviceFee){
                                             $secondFee = $deviceFee-$deviceProfit;
                                         }
                                         $firstFee = number_format($deviceFee - $secondFee, 2, '.', '');
                                         if ($secondFee > 0) {
                                             $agentModel->amount += $secondFee;
                                             $agentModel->total_amount += $secondFee;
                                             $agentModel->total_fee += $order->pay_amt;
                                             $agentModel->save();
                                             AgentAmountLog::create([
                                                 'agent_id' => $agentModel->id,
                                                 'type' => $order->type,
                                                 'amount' => $secondFee,
                                                 'order_id' => $order->id,
                                                 'device_amount'=>$deviceFee,
                                                 'log' => '设备管理费收入',
                                                 'agent_type' => 2
                                             ]);
                                         }
                                     }
                                     if ($firstFee > 0) {
                                         $firstFee-=$deviceProfit;
                                         $firstAgent->amount += $firstFee;
                                         $firstAgent->total_amount += $firstFee;
                                         $firstAgent->total_fee += $order->pay_amt;
                                         $firstAgent->save();
                                         AgentAmountLog::create([
                                             'agent_id' => $firstAgent->id,
                                             'type' => $order->type,
                                             'amount' => $firstFee,
                                             'device_amount'=>$deviceFee,
                                             'order_id' => $order->id,
                                             'log' => '设备管理费收入',
                                             'agent_type' => 2
                                         ]);
                                     }
                                 } else {
                                     if ($agentModel->rate) {
                                         if ($agentModel->rate > 0.3) {
                                             $agentModel->rate = 0.3;
                                         }
                                         $secAmount = number_format($order->pay_amt * $agentModel->rate / 100, 2, '.', '');
                                         AgentAmountLog::create([
                                             'agent_id' => $agentModel->id,
                                             'type' => $order->type,
                                             'amount' => $secAmount,
                                             'order_id' => $order->id,
                                             'log' => '电费充值（线上）分润收入'
                                         ]);

                                         $agentModel->amount += $secAmount;
                                         $agentModel->total_amount += $secAmount;
                                         $agentModel->total_fee += $order->pay_amt;
                                         $agentModel->save();
                                         $firstAmount = $allRate - $secAmount;
                                         if ($firstAmount > 0 && $agentModel->pid) {
                                             AgentAmountLog::create([
                                                 'agent_id' => $firstAgent->id,
                                                 'type' => $order->type,
                                                 'amount' => $firstAmount,
                                                 'order_id' => $order->id,
                                                 'log' => '电费充值（线上）分润收入'
                                             ]);
                                             $firstAgent->amount += $secAmount;
                                             $firstAgent->total_amount += $secAmount;
                                             $firstAgent->total_fee += $order->pay_amt;
                                             $firstAgent->save();
                                         }
                                     }
                                 }
                             } catch (\Exception $e) {

                             }
                         }
                     }
                     // 写入账单
                     // 生成电费账单
                     $bill = new Bill();
                     if($order->device->type == 2){
                         $type = OrderType::WATER;
                         $title = '水费充值:'.$order->du.'吨';
                     }else{
                         $type = OrderType::ELECTRIC;
                         $title = '电费充值:'.$order->du.'度';
                     }
                     $check = Bill::where('type',$type)
                         ->where('paid_at',$order->paid_at)
                         ->where('device_id',$order->device_id)
                         ->first();
                     if($check){
                         Log::info('已有该账单无需重复操作----'.$order->id);
                         return ;
                     }
                     $bill->fill([
                         'business_id' => $order->business_id,
                         'mobile' => $order->user->mobile,
                         'house_id' => $order->house_id,
                         'device_id' => $order->device_id,
                         'title' => $title,
                         'amount' => $amount,
                         'type' => $type,
                         'is_paid' => 1,
                         'paid_at' => $order->paid_at,
                         'target_id' => $order->id
                         //'pay_date' => now()->toDateString(),
                     ]);
                     $bill->save();
                     // 写入房东余额
                     $fd = $order->business->user;
                     $fd->amount += $amount;
                     $fd->total_amount += $amount;
                     $fd->save();
                     if($fd->sub_1 == 1 && $fd->sub_status == 1 && $fd->openid){
                         dispatch(new PushMessage($order,$fd->openid));
                     }
                     // 写入账户明细
                     UserAmountLog::create([
                         'user_id' => $fd->id,
                         'type' => $order->type,
                         'amount' => $amount,
                         'order_id' => $order->id,
                         'log' => '线上支付收入'
                     ]);
                     // 写入房东消息
                     Message::create([
                         'user_id'=> $fd->id,
                         'title' => '账单支付成功通知',
                         'content' => '支付项目：' . $order->goods_desc . ' <br> 到账金额：￥' . $amount
                     ]);

                     $billPay = new BillPay();
                     $billPay->fill([
                         'sn' => $order->order_no,
                         'bill_id' => $bill->id,
                         'amount' => $amount,
                         'payment' => $order->pay_channel == 'wx_lite' ? 4 : 5,
                         'is_paid' => 1,
                         'paid_at' => $order->paid_at,
                     ]);
                     $billPay->save();
                     if($fd->account_id && $fd->auto_cash){
                         if($fd->is_disabled == 1){
                             $errorLog = new CashDisabled();
                             $errorLog->error_msg = '账户异常(被禁用)';
                             $errorLog->amount = $amount;
                             $errorLog->user_id = $user->id;
                             $errorLog->mobile = $user->mobile;
                             $errorLog->save();
                             Log::info('订单自动打款---'.$order->number.'账户异常 请联系客服400-926-2566');
                         }
                         $all_device = Device::query()->where('business_id',$fd->business->id)->get(['id']);
                         $val = 0;
                         foreach($all_device as $v){
                             $key = $v->id.'-'.date('Ym');
                             if (Redis::exists($key)) {
                                 $val += Redis::get($key);
                             }
                         }
                         Log::info('auto-val---'.$val);
                         if ($fd->white != 1 && $val<200*1000) {
                             $checkFirst = UserCashLog::query()->where('user_id', $fd->id)
                                 ->where('status', 1)->count();
                             Log::info('auto-checkfirst---'.$checkFirst);
                             if ($amount <= 300 && $checkFirst == 0) {

                             } else {
                                 $total = Device::query()->where('business_id', $fd->business->id)->sum('total');
                                 Log::info('auto-total---'.$total);
                                 if ($total < 100) {
                                     $count = Device::query()
                                         ->where('business_id', $fd->business->id)
                                         ->where('net_type',1)
                                         ->where('total_money','>',0)
                                         ->count();
                                     Log::info('auto-count---'.$count);
                                     $useCount = Device::query()
                                         ->where('business_id', $fd->business->id)
                                         ->where('total','>=',3)
                                         ->where('net_type',1)
                                         ->count();
                                     Log::info('auto-useCount---'.$useCount);
                                     //  Log::info('count---'.$count.'---useCount----'.$useCount);
                                     if($useCount < $count*0.5){
                                         $errorLog = new CashDisabled();
//                        $errorLog->error_msg = '该用户名下'.$count.'台设备'.',总电量超过3度的为'.$useCount.'台设备,'.'名下所有表的总电量为'.$total.'度';
                                         $errorLog->error_msg ='用电异常-自动打款失败';
                                         $errorLog->amount = $amount;
                                         $errorLog->user_id = $fd->id;
                                         $errorLog->mobile = $fd->mobile;
                                         $errorLog->save();
                                         $business = Business::query()->where('user_id',$fd->id)->first();
                                         if($business->agent_id <= 0 ){
                                             Log::info('订单自动打款---'.$order->number.'尊敬的业主：本小程序仅限水电费充值，经系统分析收款行为疑似异常导致自动打款失败，平台将于7个工作日内原路退还充值款。如有疑义请联系客服：400-926-2566');
                                             return;
                                         }else{
                                             $agent = Agent::where('id',$business->agent_id)->first();
                                             if($agent->tel_no){
                                                 $tel_no = $agent->tel_no;
                                             }else{
                                                 $tel_no = $agent->mobile;
                                             }
                                             Log::info('订单自动打款---'.$order->number.'尊敬的业主：本小程序仅限水电费充值，经系统分析收款行为疑似异常导致自动打款失败，平台将于7个工作日内原路退还充值款。如有疑义请联系客服：'.$tel_no);
                                             return ;
                                         }
                                     }
                                 }
                             }
                         }
                         $bfAccount  = app::make(BaofuPay::class);
                         $drawResult['balance'] = $bfAccount->subAccount($amount,$fd);
                         if($drawResult['balance']['retCode'] != 1 || $drawResult['balance']['state'] != 1){
                             Log::info('auto-balance'.json_encode($drawResult['balance']).'---'.$amount);
                             return ;
                         }
                         $orderNo = Tools::getTsnOderid("TSN");
                         $save = [
                             'order_no' => $orderNo,
                             'cash_type' =>'自动到账',
                             'cash_amt' => $amount,
                             'user_id' => $fd->id,
                             'bank_name' => $fd->bank->bank_name,
                             'card_id' => $fd->bank->card_id,
                             'card_type' => $fd->bank->bank_acct_type,
                             'card_name' => $fd->bank->card_name
                         ];
                         $cashLog = UserCashLog::create($save);
                         $drawResult['draw'] = $bfAccount->transferCash($amount,$fd,$orderNo);
                         if($drawResult['draw']['retCode'] != 1 || $drawResult['draw']['state'] != 1){
                             Log::info('auto-draw'.json_encode($drawResult['draw']));
                             return ;
                         }
                         $fd->amount -= $amount;
                         $fd->save();
                         // 写入账户明细
                         UserAmountLog::create([
                             'user_id' => $fd->id,
                             'type' => 5,
                             'amount' => $amount,
                             'log' => '提现支出'
                         ]);
                         // 写入记录
                         $cashLog->error_msg = json_encode($drawResult);
                         $cashLog->status = 2;
                         $cashLog->save();
                     }
                 }else{
                     if($order->recharge_status == 1){
                         $order->recharge_status = 2;
                         $order->save();
                         $order->setCache();
                         // 增加日志
                         $service = app()->make(DeviceService::class);
                         $service->addRechargeFailLog($order->device_id, $order->du, $order->pay_amt,$device->du,$device->du);
                     }
                 }
            }
            Redis::del('CHECK_CACHE_'.$this->order_no);
        }catch (\Exception $e){
            Redis::del('CHECK_CACHE_'.$this->order_no);
            Log::info($e->getMessage());
        }
    }
}

